#!/usr/bin/env python
# -*- coding: utf-8 -*-

import rospy, sys
import moveit_commander

import tf.transformations as tfs
import numpy as np
import math

from moveit_msgs.msg import RobotTrajectory
from trajectory_msgs.msg import JointTrajectoryPoint
from geometry_msgs.msg import PoseStamped, Pose
from std_msgs.msg import UInt8
from std_msgs.msg import Float64MultiArray
from webots_ros.msg import RecognitionObject


class MoveItFkDemo:
    def __init__(self):
        # 初始化move_group的API
        moveit_commander.roscpp_initialize(sys.argv)
        # 初始化ROS节点
        rospy.init_node('moveit_fk_demo')

        self.enable_flag = 0
        self.objects_info = ['can','model']  
        self.camera_to_base_R_T = None
        camera_to_chassis_base_R = None
        self.cal_R_T()

        # 初始化需要使用move group控制的机械臂中的self.arm group
        self.arm = moveit_commander.MoveGroupCommander('ls')
                
        # 获取终端link的名称
        self.end_effector_link = self.arm.get_end_effector_link()
                        
        # 设置目标位置所使用的参考坐标系
        reference_frame = 'base_link'
        self.arm.set_pose_reference_frame(reference_frame)
                
        # 当运动规划失败后,允许重新规划
        self.arm.allow_replanning(True)
        
        # 设置位置(单位：米)和姿态（单位：弧度）的允许误差
        self.arm.set_goal_position_tolerance(0.001)
        self.arm.set_goal_orientation_tolerance(0.001)
        
        rospy.Subscriber('/sign', UInt8, self.get_object_info_callback)
        rospy.Subscriber('/lsarm/kinect_color/recognition_objects', RecognitionObject, self.get_object_info_callback)
        rospy.spin()

    def get_sign_callback(self,msg_sign):
        self.enable_flag = msg_sign.data

    def get_object_info_callback(self,msg_object_info):
        if(self.enable_flag == self.objects_info.index(msg_object_info.model)):
            ob_to_camera = (np.array([[msg_object_info.position.x,msg_object_info.position.y,msg_object_info.position.z,1]])).T

            ob_to_base = np.dot(self.camera_to_base_R_T,ob_to_camera)
            print("--------------")
            print(ob_to_base)

            self.set_pose(ob_to_base)

    def cal_R_T(self):
            camera_to_chassis_base_R = tfs.euler_matrix(-0.261795,-1.5708,0,'sxyz')
            camera_to_chassis_base_T = (np.array([[0,1.08+0.05,0,1]])).T
            for i in range(3):
                camera_to_chassis_base_R[i,3] = camera_to_chassis_base_T[i,0]

            chassis_base_to_arm_R = (tfs.euler_matrix(-1.5708,0,0)).T
            chassis_base_to_arm_T = -np.dot(chassis_base_to_arm_R,(np.array([[0,0.06,0,1]])).T)
            for i in range(3):
                chassis_base_to_arm_R[i,3] = chassis_base_to_arm_T[i,0]

            self.camera_to_base_R_T = np.dot(chassis_base_to_arm_R,camera_to_chassis_base_R)

    def set_pose(self,taget_pose):
        #simple ik
        y = taget_pose[2,0]
        theta0 = 0.7
        l0 = 0.112
        l1 = 0.6035+0.0415
        l2 = 0.1175
        l3 = 0.14
        f1 = 0.9323
        PI = 3.141592
        theta1 = math.asin((y+theta0-f1)/l1) + PI/2
        theta3 = PI/2 - theta1 
        
        joint_positions = [theta0,theta1,0,theta3,0]
        print(joint_positions)
        self.arm.set_joint_value_target(joint_positions)
        rospy.sleep(2)
        self.enable_flag = -1
        # 关闭并退出moveit
        moveit_commander.roscpp_shutdown()
        moveit_commander.os._exit(0)

if __name__ == "__main__":
    try:
        MoveItFkDemo()
    except rospy.ROSInterruptException:
        pass


# y = 0.6

# theta0 = 0.7
# l0 = 0.112
# l1 = 0.6035+0.0415
# l2 = 0.1175
# l3 = 0.14
# f1 = 0.9323
# PI = 3.141592
# theta1 = math.asin((y+theta0-f1)/l1) + PI/2
# theta3 = PI/2 - theta1 

# x = math.cos(theta1-PI/2)*l1 + l2 + l0

# print(theta1)
# print(theta3)
# print(x)